package com.music
{
	import flash.events.*;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundMixer;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;

	public class MusicPlayer
	{
		protected static var _instance:MusicPlayer;
		
		private var sound:Sound;
		
		private var channel:SoundChannel = new SoundChannel();
		private var arrayIndex:int = 0;
		private var songList:Array = [];
		public function MusicPlayer() 
		{
		}
		public static function instance():MusicPlayer
		{
			if( _instance == null ) _instance = new MusicPlayer();
			return _instance;
		}
		private function soundCompleteHandler(evt:Event):void 
		{
			channel =  sound.play();
			
			channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
		}
		private function selectPlay( ):void 
		{
			sound = null;
			sound = new Sound();
			
			sound.load(new URLRequest(songList[arrayIndex]));
			sound.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);            
			sound.addEventListener(Event.COMPLETE, completeHandler);
		
			stop();
			play();
		}
		private function completeHandler(event:Event):void
		{
			sound.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);            
			sound.removeEventListener(Event.COMPLETE, completeHandler);
		}
		private function errorHandler(evt:IOErrorEvent):void 
		{
			trace("The sound could not be loaded");
		}
		public function selectMusic( index:int ):void
		{
			trace(index ,  songList.length)
			if( index >=  songList.length ) return;
			arrayIndex = index;
			selectPlay();
		}
		public function get musicIndex():int
		{
			return arrayIndex;
		}
		public function play():void
		{
			if( channel == null ) return;
			var pausePosition:int = channel.position;
			channel =  sound.play(pausePosition);

			setVolume( _volume )
			if( channel != null ) channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);

			if(channel!=null)channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);

		}
		public function stop():void
		{
			if( channel != null ) channel.stop();
			if( channel != null ) channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
		}
		private var _volume:Number = 1;
		public function setVolume( value:Number = 0 ):void
		{
			if(channel==null)return ;
			_volume = value;
			var transform:SoundTransform = channel.soundTransform;
            transform.volume = _volume;
            channel.soundTransform = transform;
		}
	}
}